package com.tianji.aigc.config;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.tianji.aigc.memory.RedisChatMemoryRepository;
import com.tianji.aigc.tools.CourseTools;
import com.tianji.aigc.tools.OrderTools;
import com.tianji.aigc.vo.ChatEventVO;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;

@Configuration
public class SpringAIConfig {

    @Value("${tj.ai.memory.max:100}")
    private Integer MAX_MESSAGES;

    /**
     * 创建一个 ChatClient 对象，用于处理聊天请求。
     *
     * @param model 模型对象，用于处理聊天请求。
     * @return ChatClient 对象。
     */
    @Bean
    public ChatClient chatClient(DashScopeChatModel model,
                                 ChatMemory memory,
                                 CourseTools courseTools,
                                 OrderTools orderTools) {
        return ChatClient.builder(model)
                .defaultAdvisors(
                        SimpleLoggerAdvisor.builder().build(),
                        MessageChatMemoryAdvisor.builder(memory).build()
                )
                .defaultTools(courseTools, orderTools)
                .build();
    }

    @Bean
    public ChatClient titleClient(DashScopeChatModel model) {
        return ChatClient.builder(model).build();
    }

    @Bean
    public ChatMemory RedisChatMemory(RedisChatMemoryRepository redisChatMemoryRepository) {
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(redisChatMemoryRepository)
                .maxMessages(MAX_MESSAGES)
                .build();
    }

    @Bean
    public RedisChatMemoryRepository redisChatMemoryRepository() {
        return new RedisChatMemoryRepository();
    }
}
